<template>
  <div class="box">
    <div class="container">
      <el-form
        ref="loginForm"
        label-position="top"
        label-width="80px"
        :model="loginForm"
        :rules="rules"
      >
        <h1>登录</h1>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="loginForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-button type="primary" @click="login" :loading="isLoading"
          >登录</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginApi } from "@/api/user.js";
export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        phone: "18201288771",
        password: "111111",
      },
      rules: {
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { pattern: /^1\d{10}$/, message: "手机号不合法", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "温馨提示：密码在3~10位之间",
            trigger: "blur",
          },
        ],
      },
      isLoading: false, // 是否请求中
    };
  },
  methods: {
    login() {
      this.isLoading = true;
      this.$refs.loginForm
        .validate()
        .then(() => {
          // 验证通过，可以发送登录信息给接口
          return loginApi(this.loginForm);
        })
        .then((res) => {
          const { data } = res;
          if (data.success) {
            this.$message.success("登录成功！"); // 弹出提示信息
            // 必须先有token，才能跳转（否则会报错）
            this.$store.commit("changeToken", data.content);
            this.$router.push({
              // 路由跳转
              name: "home",
            });
            // 登录成功后将token存储到Vuex中
            console.log("login组件", res);
          } else {
            this.$message.error("账号或密码错误！");
          }
        })
        .catch(() => {
          // 表单验证失败
          this.$message.error("页面404错误！");
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
  },
};
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100vh;
  background-image: url("./img/bg.jpg");
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;

  .container {
    width: 500px;
    height: 350px;
    border: 1px solid #f3ebeb;
    background-color: rgba(255, 255, 255, 0.6);
    box-shadow: 0px 3px 15px 10px #fff;
    border-radius: 10px;
    display: flex;
    align-items: center;

    .el-form {
      height: 94%;
      margin-left: 93px;
      .el-input {
        width: 150%;
      }
      .el-button {
        width: 100%;
        margin-left: 50px;
      }
    }
  }
}
</style>
